package com.kt.silenceinstalldemo

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.kt.silenceinstalldemo.databinding.MainActivityBinding
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

/**
 * @Author Xzh
 * @Date 2025/1/24
 * @Description
 */
class MainActivity : AppCompatActivity() {

    companion object{
        const val TAG = "MainActivity"
    }

    private val binding by lazy {
        MainActivityBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        initView()
    }

    private fun initView() {
        binding.btnInstallRoot.setOnClickListener {

        }

        binding.btnCmd.setOnClickListener {
            val cmd =    binding.edtCmd.text.toString()
            Log.e(TAG, "onTextChanged: ${cmd}", )
            exCmd(cmd)
        }

        binding.edtCmd.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
              if (s == "\n"){
                  //执行命令
               val cmd =    binding.edtCmd.text.toString()
                  Log.e(TAG, "onTextChanged: ${cmd}", )
                  exCmd(cmd)
              }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })
    }

    object MyCoroutineScope {
        private val coroutineContext = Job() + Dispatchers.Default + CoroutineName("my_context")
        val coroutineScope = CoroutineScope(coroutineContext)
    }

    private fun exCmd(cmd : String){
        runBlocking {
            launch {
                val exResult = MyCoroutineScope.coroutineScope.async(Dispatchers.Default) {
                    AppInstallHelper.runRootCmd(cmd)
                }
                val result = exResult.await()
                runOnUiThread { binding.tvMessage.text = result }
            }
        }

    }


    private fun openFileEx() {
        val intent = Intent()
    }
}